import result from "./result";

const constantRouterComponents = {
    Main: () =>
        import ('@/components/Main/Main')
}


/**
 * @returns {Promise<Router>}
 * 
 */

export function generatorDynamicRouter() {
    return new Promise((resolve, reject) => {
        var results = result.data;
        var menuNav = listToTree(results, 0)
        var routers = generator(menuNav)
        resolve(routers)
    })
}

function listToTree(list, pid) {
    var reslist = []
    list.forEach(val => {
        if (val.pid == pid) {
            val.child = [];
            val.child = listToTree(list, val.id);
            if (val.child.length <= 0) delete val.child;
            reslist.push(val)
        }
    })
    return reslist
}

function generator(routerMap, parent) {

    return routerMap.map(item => {
        var meta = item.meta || {}
        let routerItem = {
                path: item.path,
                name: generatorName(item.path),
                hidden: item.hidden,
                component: (constantRouterComponents[item.component]) || (() =>
                    import (`@/views${item.component}`)),
                // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
                meta: {
                    title: meta.title,
                    icon: meta.icon || undefined,
                    target: meta.target || '_self',
                    keepAlive: meta.keepAlive || false,
                    pname: parent && parent.name || ''
                }
            }
            // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
        if (!routerItem.path.startsWith('http')) {
            routerItem.path = routerItem.path.replace('//', '/')
        }
        item.redirect && (routerItem.redirect = item.redirect)
        if (item.child && item.child.length > 0) {
            // Recursion
            routerItem.children = generator(item.child, routerItem)
            if (routerItem.children.length <= 0) delete routerItem.children;

        }

        return routerItem
    })
}

function generatorName(path) {
    if (path[0] == '/') {
        path = path.substring(1)
    }

    var respath = path.replace(/\//g, '_')
    return respath
}